package com.keqiang.chart.animation

import android.animation.Animator
import android.animation.ValueAnimator
import android.animation.ValueAnimator.AnimatorUpdateListener

/**
 * 执行图表绘制动画
 *
 * @author Created by wanggaowan on 2022/7/27 17:07
 */
open class Animator {
    private var mAnimator: ValueAnimator? = null

    /**
     * 获取动画进度
     */
    fun getProgress(): Float {
        return mAnimator?.animatedValue as Float? ?: 1f
    }

    /**
     * 动画是否执行
     */
    fun isStart(): Boolean {
        return mAnimator?.isStarted ?: false
    }

    /**
     * 开始执行动画
     */
    @JvmOverloads
    fun start(duration: Long, updateListener: AnimatorUpdateListener? = null, listener: Animator.AnimatorListener? = null) {
        stop()
        val ofFloat = ValueAnimator.ofFloat(0f, 1f)
        mAnimator = ofFloat
        ofFloat.duration = duration
        updateListener?.let {
            ofFloat.addUpdateListener(it)
        }
        listener?.let {
            ofFloat.addListener(it)
        }
        ofFloat.start()
    }

    /**
     * 结束动画执行
     */
    fun stop() {
        if (isStart()) {
            mAnimator?.cancel()
            mAnimator = null
        }
    }
}